package com.manage.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

@SuppressWarnings("deprecation")
public class RequestPostTest {

	private static HttpClient client = null;

	private static final int TIMEOUT = 10000;

	private static String url = "http://112.124.19.171:8088/beautyshop/update.do";
	String json = "{\"beautyshopId\":1,\"currentPage\":0,\"pageSize\":0}";

	public RequestPostTest() {
		List<NameValuePair> pairList = getcarfee();
		try {
			HttpResponse response = doHttpsPost(url, pairList);
			BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			String line = null;
			StringBuffer result = new StringBuffer();
			while ((line = br.readLine()) != null) {
				result.append(line).append("\n");
			}
			if (result.length() > 0) {
				result.deleteCharAt(result.length() - 1);
			}
			System.out.println("Result:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new RequestPostTest();
	}

	public List<NameValuePair> getcarfee() {
		List<NameValuePair> pairList = new ArrayList<NameValuePair>();
		// String json =
		// "{\"beautyshopId\":1,\"beautyshopName\":\"sbbbb2123\",\"beautyshopAddress\":\"123333333\",\"beautyshopBoss\":\"sb\",\"beautyshopPhone\":\"1234444444444\",\"createTime\":\"Oct
		// 10, 2015 2:51:29 PM\",\"updateTime\":\"Oct 10, 2015 2:51:29
		// PM\",\"currentPage\":0,\"pageSize\":0}";"updateTime":"2015-10-14
		// 14:59:54"
		String json = "{\"currentPage\":0,\"pageSize\":0,\"startDate\":null,\"endDate\":null,\"beautyshopId\":2,\"beautyshopName\":\"123\",\"beautyshopAddress\":\"123\",\"beautyshopBoss\":\"123\",\"beautyshopPhone\":\"12312341234\",\"createTime\":\"2015-10-14 14:59:54\",\"updateTime\":\"2015-10-14 14:59:54\",\"start\":0}";
		NameValuePair v0 = new BasicNameValuePair("data", json);
		pairList.add(v0);
		return pairList;
	}

	/**
	 * Post请求连接Https服务
	 * 
	 * @param serverURL
	 *            请求地址
	 * @param jsonStr
	 *            请求报文
	 * @return
	 * @throws Exception
	 */
	public static synchronized HttpResponse doHttpsGet(String serverURL) {
		// 参数
		HttpParams httpParameters = new BasicHttpParams();
		// 设置连接超时
		HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT);
		// 设置socket超时
		HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT);
		// 获取HttpClient对象 （认证）
		HttpClient hc = initHttpClient(httpParameters);
		// 请求报文
		HttpResponse response = null;
		try {
			HttpGet get = new HttpGet(new URI(serverURL));
			response = hc.execute(get);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * Post请求连接Https服务
	 * 
	 * @param serverURL
	 *            请求地址
	 * @param jsonStr
	 *            请求报文
	 * @return
	 * @throws Exception
	 */
	public static synchronized HttpResponse doHttpsPost(String serverURL, List<NameValuePair> pairList)
			throws Exception {
		// 参数
		HttpParams httpParameters = new BasicHttpParams();
		// 设置连接超时
		HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT);
		// 设置socket超时
		HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT);
		// 获取HttpClient对象 （认证）
		HttpClient hc = initHttpClient(httpParameters);
		HttpPost post = new HttpPost(serverURL);
		post.setEntity(new UrlEncodedFormEntity(pairList, HTTP.UTF_8));
		post.setParams(httpParameters);
		HttpResponse response = null;
		try {
			response = hc.execute(post);
		} catch (UnknownHostException e) {
			throw new Exception("Unable to access " + e.getLocalizedMessage());
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 初始化HttpClient对象
	 * 
	 * @param params
	 * @return
	 */
	public static synchronized HttpClient initHttpClient(HttpParams params) {
		if (client == null) {
			try {
				SSLSocketFactory sf = SSLSocketFactoryImp.getSocketFactory();
				// 允许所有主机的验证
				sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
				HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
				// 设置http和https支持
				SchemeRegistry registry = new SchemeRegistry();
				registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
				registry.register(new Scheme("https", sf, 443));
				ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
				return new DefaultHttpClient(ccm, params);
			} catch (Exception e) {
				e.printStackTrace();
				return new DefaultHttpClient(params);
			}
		}
		return client;
	}

	public static class SSLSocketFactoryImp
			extends SSLSocketFactory {
		final SSLContext sslContext = SSLContext.getInstance("TLS");

		public SSLSocketFactoryImp(KeyStore truststore)
				throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
			super(truststore);

			TrustManager tm = new X509TrustManager() {
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				@Override
				public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
						throws java.security.cert.CertificateException {
				}

				@Override
				public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
						throws java.security.cert.CertificateException {
				}
			};
			sslContext.init(null, new TrustManager[] { tm }, null);
		}

		@Override
		public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
				throws IOException, UnknownHostException {
			return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
		}

		public Socket createSocket() throws IOException {
			return sslContext.getSocketFactory().createSocket();
		}

		public static SSLSocketFactory getSocketFactory() {
			KeyStore trustStore;
			try {
				trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
				trustStore.load(null, null);
				SSLSocketFactory sf = new SSLSocketFactoryImp(trustStore);
				return sf;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
	}
}
